#if UNITY_ANDROID
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using FibMatrix.IO;
using FM_Mono;
using UnityEngine;

[IgnoreGen]
public class AndroidScriptConfig:MobileScriptConfig
{
    private const string CONFIG_XML = "mono_android_config.xml";
    private string _libDir;
    public override string libraryDirectory
    {
        get
        {
            if (_libDir == null)
            {
                _libDir = DetermineAppNativeLibDir();
            }
            return _libDir;
        }
    }

    public override string configDirectory
    {
        get
        {
            return null;
        }
    }

    private string _overrideConfig;
    
    public override string overrideConfig
    {
        get
        {
            if (_overrideConfig == null)
            {
                if (PackageManager.Exists(CONFIG_XML))
                {
                    _overrideConfig = Encoding.UTF8.GetString(PackageManager.ReadAllBytes(CONFIG_XML));
                }
                else
                {
                    _overrideConfig = "";
                }
            }

            return _overrideConfig;
        }
    }
    public AndroidScriptConfig(List<SearchPath> searchPaths, string[] packageOnlyAssemblies) : base(new List<SearchPath>(), packageOnlyAssemblies)
    {
        // Android底层的AAssetManager_open接收包内路径要去掉 "jar:file:///xxx/xx.apk!/assets/" 前缀
        foreach (var searchPath in searchPaths)
        {
            var prefix = searchPath.GetRootFullPath();
            var type = (MobilePersistType)(int)searchPath.persistType;
            if (searchPath.persistType == PersistType.Package && prefix.StartsWith(Application.streamingAssetsPath))
            {
                var oldPrefix = prefix;
                prefix = prefix.Substring(Application.streamingAssetsPath.Length + 1);
                Debug.Log($"AndroidScriptConfig去除包内前缀，从{oldPrefix} 改为：{prefix}");
            }
            Debug.Log($"AndroidScriptConfig AddAssemblySearchPath prefix:{prefix} type:{type}");
            AddAssemblySearchPath(prefix, type);
        }
    }

    private string DetermineAppNativeLibDir() {
        using (var nativeHelperClass = new AndroidJavaClass("com.rivergame.util.RGNativeHelper"))
        {
            var nativeLibraryDir = nativeHelperClass.CallStatic<string>("getNativeLibPath");
            return nativeLibraryDir;
        }
    }
}
#endif